package leetcode;

import java.util.HashMap;
import java.util.HashSet;

public class thirdteen2 {
    //https://leetcode.cn/problems/fruit-into-baskets/
    public static int totalFruit(int[] fruits) {
        int left;
        int right;
        int max=0;
        int n=fruits.length;
        HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
        //水果种类个数，该种类水果的个数
        for(right=0,left=0;right<n;right++){
            int in=fruits[right];
            map.put(in,map.getOrDefault(in,0)+1);//若in有值，直接加1，无值，返回0加1
            while(map.size()>2){
                max=Math.max(right-left,max);
                int out=fruits[left];
                map.put(out,map.get(out)-1);
                if(map.get(out)==0){
                    map.remove(out);
                }
                left++;

            }
            max=Math.max(right-left+1,max);


        }
        return max;


    }

    public static void main(String[] args) {
        int[] array={1,2,3,2,2};
        int i = totalFruit(array);
        System.out.println(i);
    }
}
